<template>
  <div class="header-container">
    <div class="left">
      <span class="time">{{ currentTime }}</span>
      <span class="week">{{ currentDay }}</span>
      <div class="action-btn h3yun-btn" v-if="hasVideo && !isAdmin" @click="videoManage" style="margin-left: 20px;">
        <el-icon><VideoCamera /></el-icon>
        <span>主监控点管理</span>
      </div>
      <div class="action-btn h3yun-btn" v-if="hasTree" @click="goToH3Yun" style="margin-left: 20px;">
        <el-icon><HomeFilled /></el-icon>
        <span>后台</span>
      </div>
      <div class="action-btn h3yun-btn" v-if="!isAdmin && hasTree" @click="openReportDialog" style="margin-left: 20px;">
        <el-icon><DataLine  /></el-icon>
        <span>报表统计</span>
      </div>
    </div>
    <div class="center" :style="{'font-size': TextFontSize + 'px'}">
      {{ title }}
    </div>
    <div class="right">
      <el-tree-select size="small" ref="treeSelectRef" v-model="selectedArea" :data="treeData" placeholder="请选择区域" class="tree-select"
      :check-strictly="true"
      :default-expand-all="true"
      :filter-node-method="filterNodeMethod"
      filterable
      @current-change="handleTreeChange"
      style="
        --el-tree-node-hover-bg-color: rgba(45, 120, 219, 1);
        --el-tree-node-selected-bg-color: rgba(45, 120, 219, 1);
        --el-select-multiple-input-color: rgb(255, 255, 255);
        --el-tree-node-active-bg-color: rgba(45, 120, 219, 1);
      ">
        <template #prefix>
          <el-icon style="color: rgba(255, 255, 255, 0.8); font-size: 15px;"><OfficeBuilding /></el-icon>
        </template>
      </el-tree-select>
      <div class="action-btn" v-if="showVideoBtn && isAdmin" @click="goVideo" style="margin-right: -10px;">
        <el-icon><VideoPlay /></el-icon>
        <span>视频</span>
      </div>
      <div class="action-btn" v-if="showScreenBtn" @click="goDataBoard" style="margin-right: -10px;">
        <el-icon><Monitor /></el-icon>
        <span>大屏</span>
      </div>
      <el-button @click="toggleFullScreen" class="full-screen-btn">
        <el-icon>
          <FullScreen v-if="!isFullscreen" />
          <Aim v-else />
        </el-icon>
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeMount, onBeforeUnmount, computed } from 'vue'
import { ElTreeSelect, ElButton, ElIcon } from 'element-plus'
import { FullScreen, Aim, VideoCamera, HomeFilled, Monitor, VideoPlay, OfficeBuilding, DataLine  } from '@element-plus/icons-vue'
import 'element-plus/dist/index.css'
import { getPowerRegionTree, getCommonConfig } from '@/api/h3yun'
import { useUserStore } from '@/store/userStore'

const emit = defineEmits(['treeChange', 'openVideoManage', 'openReport'])

// 定义props，设置标题默认值
const props = defineProps({
  title: {
    type: String,
    default: '数智化污水处理大屏'
  },
  hasTree: {
    type: Boolean,
    default: true
  },
  hasVideo: {
    type: Boolean,
    default: false
  },
  isAdmin: {
    type: Boolean,
    default: false
  },
  TextFontSize: {
    type: Number,
    default: 30
  }
})
const userStore = useUserStore()

const showVideoBtn = computed(() => window.location.href.includes('screen'))
const showScreenBtn = computed(() => window.location.href.includes('video'))

const currentTime = ref('')
const currentDay = ref('')
const isFullscreen = ref(false)
const selectedArea = ref('')

const powerCode = computed(() => userStore.userInfo?.powerCode)

const treeData: any = ref<any[]>([])
const allLeafNodes = ref<any[]>([])
const currentLeafIndex = ref(0)
const pollTimeMinutes = ref(10) // 默认10分钟
let leafNodeTimer: number | null = null

const filterNodeMethod = (value: string, data: any) => data.label.includes(value)

const treeSelectRef = ref()
const handleTreeChange = (value: any) => {
  let params = {
    ...value,
    name: value.label
  }
  //失去当前输入框focus
  treeSelectRef.value.blur()
  emit('treeChange', params)
}

const formatDate = (date: Date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

const updateTime = () => {
  const now = new Date()
  currentTime.value = formatDate(now)
  currentDay.value = now.toLocaleDateString('zh-CN', { weekday: 'long' })
}

const toggleFullScreen = () => {
  if (!document.fullscreenElement) {
    document.documentElement.requestFullscreen()
    isFullscreen.value = true
  } else if (document.exitFullscreen) {
    document.exitFullscreen()
    isFullscreen.value = false
  }
}

// 跳转到氚云系统
const goToH3Yun = () => {
  window.open('https://www.h3yun.com/application/D001729axy20rsfk5k9fndomy/dteefbpoukibyt7wfz6y')
}

const videoManage = () => {
  emit('openVideoManage')
}

const goDataBoard  = () => {
  window.location.href = window.location.origin + '/screen'
}

const goVideo = () => {
  window.location.href = window.location.origin + '/video'
}

const openReportDialog = () => {
  emit('openReport')
}

// 触发叶子节点点击事件
const triggerLeafNodeClick = () => {
  if (allLeafNodes.value.length === 0) return
  
  const currentNode = allLeafNodes.value[currentLeafIndex.value]
  console.log(`自动触发叶子节点点击: ${currentNode.label}`)
  
  // 更新el-tree-select的选中值，实现UI回显
  selectedArea.value = currentNode.value
  
  // 模拟点击事件，调用handleTreeChange
  handleTreeChange(currentNode)
  
  // 更新索引，循环到下一个叶子节点
  currentLeafIndex.value = (currentLeafIndex.value + 1) % allLeafNodes.value.length
}

// 获取轮询时间配置
const fetchPollTimeConfig = async () => {
  try {
    const res = await getCommonConfig()
    if (res.code === '0' && res.data) {
      const pollConfig = res.data.find(config => config.code === 'super-hospital-poll-time')
      if (pollConfig && pollConfig.value) {
        const configMinutes = parseInt(pollConfig.value)
        if (!isNaN(configMinutes) && configMinutes > 0) {
          pollTimeMinutes.value = configMinutes
          console.log(`获取轮询时间配置成功: ${configMinutes}分钟`)
        } else {
          console.warn('轮询时间配置值无效，使用默认值10分钟')
        }
      } else {
        console.warn('未找到轮询时间配置，使用默认值10分钟')
      }
    } else {
      console.error('获取轮询时间配置失败:', res.msg)
    }
  } catch (error) {
    console.error('获取轮询时间配置异常:', error)
  }
}

// 启动叶子节点循环点击定时器
const startLeafNodeTimer = () => {
  // 清除已存在的定时器
  if (leafNodeTimer) {
    clearInterval(leafNodeTimer)
  }
  
  // 使用配置的轮询时间（分钟转毫秒）
  const intervalMs = pollTimeMinutes.value * 60 * 1000
  leafNodeTimer = setInterval(() => {
    triggerLeafNodeClick()
  }, intervalMs)
  
  console.log(`叶子节点循环点击定时器已启动，每${pollTimeMinutes.value}分钟触发一次`)
}

// 停止叶子节点循环点击定时器
const stopLeafNodeTimer = () => {
  if (leafNodeTimer) {
    clearInterval(leafNodeTimer)
    leafNodeTimer = null
    console.log('叶子节点循环点击定时器已停止')
  }
}

// 递归查找所有叶子节点
const findLeafNodes = (nodes: any[]): any[] => {
  const leafNodes: any[] = []
  
  const traverse = (nodeList: any[]) => {
    nodeList.forEach(node => {
      // 检查是否为叶子节点（没有children或children为空）
      if (!node.children || node.children.length === 0) {
        leafNodes.push({
          level: node.level || 1,
          children: [],
          label: node.label,
          value: node.value
        })
      } else {
        // 如果有子节点，继续递归查找
        traverse(node.children)
      }
    })
  }
  
  traverse(nodes)
  return leafNodes
}

// 获取区域树数据
const fetchRegionTree = async () => {
  try {
    // 先获取轮询时间配置
    await fetchPollTimeConfig()
    
    const res = await getPowerRegionTree()
    if (res.code === '0' && res.data) {
      // 构建树形结构
      const cityData = res.data
      treeData.value = powerCode.value === 'admin' ? [cityData] : cityData.children
      
      // 查找所有叶子节点
      allLeafNodes.value = findLeafNodes([cityData])
      console.log('所有叶子节点:', allLeafNodes.value)
      
      // 只有在叶子节点数量>1 且 powerCode不是admin时才启动定时任务
      if (allLeafNodes.value.length > 1 && powerCode.value !== 'admin') {
        // 首次直接触发第一个叶子节点，不等待
        triggerLeafNodeClick()
        startLeafNodeTimer()
      } else {
        console.log('定时任务未启动：', 
          allLeafNodes.value.length <= 1 ? '叶子节点数量不足' : 'admin用户无需定时切换')
        
        // 未启动定时任务时，设置默认选中值
        if (powerCode.value === 'admin') {
          selectedArea.value = cityData.value
        } else {
          // 如果是childrenOrg，则默认选中第一个子节点
          selectedArea.value = treeData.value[0].value
        }
      }

      // 根据powerCode设置禁用状态
      // if (powerCode.value === 'childrenOrg') {
      //   disableNonLeafNodes(treeData.value)
      // }
    } else {
      console.error('获取区域树数据失败:', res.msg)
    }
  } catch (error) {
    console.error('获取区域树数据异常:', error)
  }
}

// 递归获取最后一个子节点
const getLastChildNode = (node: any) => {
  if (node.children && node.children.length > 0) {
    return getLastChildNode(node.children[node.children.length - 1])
  }
  return node.value
}


// 禁用非叶子节点
const disableNonLeafNodes = (nodes: any[]) => {
  nodes.forEach(node => {
    if (node.children && node.children.length > 0) {
      node.disabled = true
      disableNonLeafNodes(node.children)
    }
  })
}

onBeforeMount(async () => {
  await fetchRegionTree()
})

onMounted(() => {
  updateTime()
  setInterval(updateTime, 1000)
  document.addEventListener('fullscreenchange', () => {
    isFullscreen.value = !!document.fullscreenElement
  })
})

onBeforeUnmount(() => {
  // 组件销毁前清除定时器
  stopLeafNodeTimer()
})
</script>

<style scoped lang="scss">
.header-container {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  z-index: 12;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  background-image: url('@/assets/images/screen/header.webp');
  background-size: 100% 100%;
  width: 100%;
  height: 90px;
  color: white;
  padding: 10px 20px;
  box-sizing: border-box;
}

:deep(.el-select-dropdown__item.is-hovering) {
  background-color: transparent !important;
  color: rgba(255, 255, 255, 0.8) !important;
}

.left {
  flex: 1;
  display: flex;

  .time {
    font-size: 14px;
    font-weight: 500;
  }

  .week {
    margin-left: 16px;
    font-size: 14px;
    opacity: 0.9;
  }
}

.center {
  flex: 2;
  flex-grow: 1;
  text-align: center;
  // font-size: 30px;
  font-family: '楷体';
  font-weight: 600;
  height: 50px;
  line-height: 50px;
}

.h3yun-btn {
  position: relative;
  top: -4px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 4px 10px;
  background-color: rgb(40, 136, 238);
  border: 1px solid rgb(40, 136, 238);
  border-radius: 2px;
  color: white;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 0 5px rgb(40, 136, 238);
  
  &:hover {
    background-color: rgb(40, 136, 238);
    transform: translateY(-1px);
  }
  
  .el-icon {
    font-size: 16px;
  }
}

.right {
  flex: 1;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 16px;
  margin-top: -6px;

  .tree-select {
    width: 200px;
  }

  .full-screen-btn {
    background: transparent;
    border: none;
    color: white;
    font-size: 20px;
    cursor: pointer;
    padding: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: -16px;
  }
}

:deep(.el-tree-select) {
  --el-select-bg-color: transparent;
  --el-fill-color-blank: transparent;
}

:deep(.el-input__wrapper) {
  background-color: transparent !important;
  box-shadow: 0 0 0 1px rgb(40, 136, 238) !important;
  border-radius: 0 !important;
}

:deep(.el-select__wrapper) {
  background-color: transparent !important;
  border: 1px solid rgb(40, 136, 238);
  border-radius: 0 !important;
  box-shadow: 0 0 0 1px rgb(40, 136, 238) !important;
}

:deep(.el-select__placeholder.is-transparent) {
  color: #fff;
}

:deep(.el-select__placeholder) {
  color: #fff;
}
</style>